import '../utils/SqlControler.dart';
import 'package:mysql1/mysql1.dart';

//数据库连接demo

class User {
  late int id;
  late String name;
  late String password;
  late String email;

  User({
    required this.id,
    required this.name,
    required this.password,
    required this.email,
  });

  factory User.fromJson(Map<dynamic, dynamic> json) {
    return User(
      id: json['id'] as int,
      name: json['name'].toString(),
      password: json['password'].toString(),
      email: json['email'].toString(),
    );
  }

  Map<String, dynamic> toJson() {
    return {'id': id, 'name': name, 'password': password, 'email': email};
  }
}

class AccountManager {
  late MySqlConnection db;
  AccountManager._() {}
  static Future<AccountManager> GetConn() async {
    var manager = AccountManager._();
    manager.db = await Sql.GetConn();
    return manager;
  }

  static Future<AccountManager> GetFromExistSql(MySqlConnection myDB) async {
    var manager = AccountManager._();
    manager.db = myDB;
    return manager;
  }

  void close() {
    db.close();
  }

  //检验密码是否相同，-1为没有该用户，0为密码错误，1为正确
  Future<User?> getUserFromName(String name) async {
    var query = Query(table: 'users', where: 'name="$name"');
    var res = (await db.query(query.toString())).toList();
    if (res.isEmpty) {
      return null;
    }
    return User.fromJson(res[0].fields);
  }
}
